<template>
  <div class="container">
    <div class="table">
      <el-table :data="tableData" style="width: 100%" :row-class-name="tableRowClassName" :scroll="getScrollData"
        height="100%" @row-click="chooseRow">
        <el-table-column prop="id" label="编号" />
        <el-table-column prop="name" label="审批类型" />
        <el-table-column label="操作">
          <template #default="scope">
            <el-button size="small" type="primary" @click="handleEdit(scope.$index, scope.row)">
              修改
            </el-button>
            <el-button size="small" type="danger" @click="handleDelete(scope.$index, scope.row)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div v-if="selectedRow == null" class="board">
      <el-text type="info" size="large">暂无审批类型被选中</el-text>
    </div>
    <div class="item" v-else>
      <el-scrollbar ref="scrollbar" @scroll="handleScroll">
        <div class="concreteBoard">
          <div class="item-content">
            <p>
              <span style="font-size: 25px; color: #021148">审批信息</span>
            </p>
            <p style="margin: 1.5%">
              <span style="font-size: 18px; color: #021148">审批类型:</span>
              <span style="font-size: 18px; color: #021148">{{
                selectedRowData?.name
              }}</span>
            </p>
            <p style="margin: 1.5%">
              <span style="font-size: 18px; color: #021148">固定审批项:</span>
            </p>
            <el-table :data="fixedItems" style="width: 80%; border-radius: 10px" height="200px">
              <el-table-column label="审批项名称">
                <template #default="scope">
                  {{ scope.row }}
                </template>
              </el-table-column>
            </el-table>
            <p style="margin: 1.5%">
              <span style="font-size: 18px; color: #021148">流动审批项:</span>
            </p>
            <el-table :data="selectedItems" style="width: 80%; border-radius: 10px" height="200px">
              <el-table-column label="审批项名称">
                <template #default="scope">
                  {{ scope.row }}
                </template>
              </el-table-column>
              <el-table-column label="操作" v-if="isUpdating">
                <template #default="scope">
                  <!-- 之后有机会再做优化 -->
                  <!-- <el-button size="small" type="primary" @click="handleEdit(scope.row)">
                编辑
              </el-button> -->
                  <el-button size="small" type="danger" @click="handleItemDelete(scope.$index)">
                    删除
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
            <p v-if="isUpdating">
              <el-button style="margin-top: 1%;" type="primary" @click="addProcessItems">增添审批项</el-button>
              <el-select v-model="processItems" multiple filterable allow-create default-first-option
                :reserve-keyword="false" placeholder="Choose items for your process" class="el-style">
                <el-option v-for="item in processOptions" :key="item.id" :label="item.name" :value="item.id" />
              </el-select>
            </p>
          </div>
          <div class="item-timestamp">
            <p>
              <span style="font-size: 25px; color: #021148">审批流程</span>
            </p>
            <div v-if="isUpdating">
              <p>
                <span style="font-size: 18px; color: #021148">待增加审核节点信息</span>
              </p>
              <p>
                <span style="font-size: 16px; color: #021148">节点名称</span>
                <el-input v-model="nodeName" @input="nodeNameValue" class="el-style" placeholder="Please input" />
              </p>
              <p>
                <span style="font-size: 16px; color: #021148">节点所处顺序</span>
                <el-input-number class="el-style" v-model="nodePriority" :min="1" :max="10" />
              </p>
              <p>
                <span style="font-size: 16px; color: #021148">此节点是否需要部门审核</span>
                <el-radio-group class="el-style" v-model="isWithDept">
                  <el-radio value="0" size="large">是</el-radio>
                  <el-radio value="1" size="large">否</el-radio>
                </el-radio-group>
              </p>
              <p v-if="isWithDept === '0'">
                <span style="font-size: 16px; color: #021148">此节点到上几级部门审核</span>
                <el-input-number class="el-style" v-model="deptId" :min="0" :max="deptLayers" />
              </p>
              <p>
                <el-button @click="addProcessNode" type="primary">增加审批节点</el-button>
              </p>
              <p>
                <span style="font-size: 18px; color: #021148">删除审核节点</span>
              </p>
              <p>
                <el-button @click="deleteProcessNode" type="warning">删除审批节点</el-button>
                <el-select v-model="readyForDelete" placeholder="Choose tags for your article"
                  style="width: 240px; margin-left: 10px">
                  <el-option v-for="(item, index) in processNodes" :key="index"
                    :label="'第' + item.nodePriority + '步 ' + item.nodeName" :value="item.nodePriority" />
                </el-select>
              </p>
            </div>
            <el-timeline style="max-width: 30vw">
              <el-timeline-item v-for="(item, index) in processNodes" :key="index">
                <span>{{ item.nodeName }}</span>
                <span style="color: #b7b7b7;" v-if="isUpdating"> 此节点所处顺序：{{ item.nodePriority }}</span>
              </el-timeline-item>
            </el-timeline>
          </div>
        </div>
        <div v-if="isUpdating">
          <el-button @click="storeChange" style="margin: 2%;width: 45%;" type="success">保存</el-button>
          <el-button @click="refuse" style="margin: 2%;width: 45%;" type="default">取消</el-button>
        </div>
        <!-- 添加滚动指示 -->
        <div class="scroll-indicator" v-show="showScrollIndicator">
          <el-icon :size="30" color="#999">
            <ArrowDown />
          </el-icon>
        </div>
      </el-scrollbar>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { onMounted, ref } from "vue";
import { ElMessage, ElMessageBox } from 'element-plus'
import { getAllTypes, getProcessDetail, updateType, deleteType } from "../../api/process.js";
import { getTreeHeight } from "../../api/dept.js";
import { get } from "../../http/request.js";
import { ArrowDown } from '@element-plus/icons-vue'
import { nextTick, watch } from 'vue'

interface processType {
  id: number;
  name: string;
}

//被选择的要显示的类型
const selectedRow = ref(null);
//被选择的类型的具体数据
//传到前端的数据一定是要经过后端处理的，只包括：流程类型名字、流程节点数组、审批项数组
const selectedRowData = ref<null | {
  name: string;
  activities: processNode[];
  processItems: string[];
}>(null);
//固定项名称，仅作展示
const fixedItems = [
  "申请人姓名",
  "申请人工号",
  "申请人部门名称",
  "申请人职称"
]

// 新增响应式变量
const showScrollIndicator = ref(true)
const scrollbar = ref()

// 修改检查滚动的方法
const checkScroll = () => {
  const wrap = scrollbar.value?.wrap$
  if (wrap) {
    const { scrollTop, clientHeight, scrollHeight } = wrap
    // 使用百分比判断（最后5%视为底部区域）
    const threshold = clientHeight * 0.05 // 容器高度的5%作为阈值
    showScrollIndicator.value = scrollHeight - (scrollTop + clientHeight) > threshold
  }
}
// 处理滚动事件
const handleScroll = () => {
  checkScroll()
}

// 当选中行变化时检查
watch(selectedRowData, () => {
  nextTick(() => {
    checkScroll()
  })
})

//是否处于修改状态
const isUpdating = ref(false);
//触发修改状态
const handleEdit = (index, row) => {
  isUpdating.value = true;
  console.log("修改", index, "行数据:", row);
  for (let i = 0; i < tableData.value.length; i++) {
    icons.value.push("el-icon-delete");
  }
  icons.value.push("el-icon-plus");
};
//进行更新
const updateProcessType = async (data) => {
  const updateRes = await updateType(data);
  if (updateRes.flag === true) {
    ElMessage({
      type: 'success',
      message: '审批类型修改成功',
    })
    //清空审批类型信息
  } else {
    ElMessage({
      type: 'error',
      message: '审批类型修改失败',
    })
  }
}
//保存修改
const storeChange = () => {
  //保存审批类型到数据库
  //传入后端的数据应该包括审批类型名称，审批项数组，审批节点数组
  console.log("审批类型名称", selectedRowData.value?.name);
  console.log("审批项", selectedItems.value);
  console.log("审批节点", processNodes.value);
  //如果没有输入审批类型名称，直接返回
  if (selectedRowData.value?.name === "") {
    ElMessage({
      type: 'warning',
      message: '审批类型名称不能为空',
    })
    return;
  }
  //如果没有选中审批项，直接返回
  if (selectedItems.value.length === 0) {
    ElMessage({
      type: 'warning',
      message: '审批项不能为空',
    })
    return;
  }
  //如果没有添加审批节点，直接返回
  if (processNodes.value.length === 0) {
    ElMessage({
      type: 'warning',
      message: '审批节点不能为空',
    })
    return;
  }
  let data = {
    processType: selectedRowData.value?.name,
    applicationItems: selectedItems.value,
    processNodes: processNodes.value,
  };
  //添加审批类型到数据库
  updateProcessType(data);
  console.log("修改审批类型", data);

  isUpdating.value = false;
  console.log("保存修改", selectedRowData.value);
};
//取消修改
const refuse = () => {
  isUpdating.value = false;
  console.log("取消修改", selectedRowData.value);
};
const icons = ref<string[]>([]);

const deleteProcessType = async (id) => {
  const res = await deleteType(id);
  if (res.flag === true) {
    ElMessage({
      type: 'success',
      message: '审批类型删除成功',
    })
  } else {
    ElMessage({
      type: 'error',
      message: '审批类型删除失败',
    })
  }
}
//删除某条数据
const handleDelete = async(index, row) => {
  ElMessageBox.confirm(
    '确定删除这个审批类型吗？',
    'Warning',
    {
      confirmButtonText: 'OK',
      cancelButtonText: 'Cancel',
      type: 'warning',
    }
  )
    .then(() => {
      deleteProcessType(row.id);
      tableData.value.splice(index, 1);
      ElMessage({
        type: 'success',
        message: 'Delete completed',
      })
      getTypesList();
      console.log("删除", index, "行数据:", row);
      // 这里可以添加删除操作的逻辑，比如发送请求到后端删除数据
      selectedRow.value = null
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: 'Delete canceled',
      })
    })
}

//选中行数据
const chooseRow = async (row) => {
  selectedRow.value = row;
  console.log("选中行数据:", row);
  //这个时候去后端请求数据，把流程类型、流程节点数组、审批项数组打包成一个对象拿过来
  //getOneType(row.id);
  try {
    const res = await getProcessDetail(row.id);
    if (res.flag === true) { // 使用 === 进行比较
      let resType = res.result;
      console.log("获取审批类型成功", resType);
      selectedRowData.value = {
        name: resType.processType,
        activities: [],
        processItems: [],
      };
      selectedRowData.value.activities = resType.processNodes.map((item) => {
        return {
          nodeName: item.nodeName,
          isWithDept: item.isWithDept,
          deptPriority: item.deptPriority,
          nodePriority: item.nodePriority,
        };
      });
      selectedRowData.value.processItems = resType.applicationItems.map((item) => {
        return item.itemName;
      });

      selectedItems.value = selectedRowData.value.processItems;
      processNodes.value = selectedRowData.value.activities
        .map((item) => {
          if (item.nodePriority > 0) {
            return {
              nodeName: item.nodeName,
              isWithDept: item.isWithDept,
              deptPriority: item.deptPriority,
              nodePriority: item.nodePriority,
            };
          }
        })
        .filter((item): item is processNode => item !== undefined);
      ElMessage({
        type: 'success',
        message: '获取审批类型成功',
      });
    } else {
      ElMessage({
        type: 'error',
        message: '获取审批类型失败',
      });
    }
  } catch (error) {
    ElMessage({
      type: 'error',
      message: '获取审批类型发生错误: ' + error.message,
    });
    console.error("获取审批类型发生错误:", error);
  }
  console.log("选中行的具体数据:", selectedRowData.value);

};

const tableRowClassName = ({
  row,
  rowIndex,
}: {
  row: processType;
  rowIndex: number;
}) => {
  if (rowIndex % 2 === 1) {
    return "odd-row";
  } else if (rowIndex % 2 === 0) {
    return "even-row";
  }
  return "";
};

//审批类型数据
const tableData = ref<processType[]>([]);

//审批项
//待输入的审批项
const processItems = ref<string[]>([]);
//可选择的审批项,从数据库拿过来的，要做处理的
const processOptions = ref<{ id: number, name: string }[]>([]);
//已经被选中的审批项
const selectedItems = ref<string[]>([]);

//暂时添加审批项
const addProcessItems = () => {
  //如果没有选中审批项，直接返回
  if (processItems.value.length === 0) {
    return;
  }
  //把选中的审批项添加到selectedItems中
  processItems.value.forEach((item: string) => {
    if (!selectedItems.value.includes(item)) {
      selectedItems.value.push(item);
    } else {
      ElMessage({
        type: 'warning',
        message: '审批项已存在，请重新选择',
      })
      return;
    }
  });
  ElMessage({
    type: 'success',
    message: '审批项添加成功',
  })
  //清空选中的审批项
  processItems.value = [];
};
//为审批项添加更复杂的属性
//之后有机会再做
// const handleEdit=(row)=>{
// }
//把选中的审批项删掉
const handleItemDelete = (index: number) => {
  selectedItems.value.splice(index, 1);
  ElMessage({
    type: 'success',
    message: '审批项删除成功',
  })
};

interface processNode {
  nodeName: string;
  isWithDept: boolean;
  deptPriority: number;
  nodePriority: number;
}
//节点名称
const nodeName = ref("");
//节点优先级
const nodePriority = ref(0);
//是否需要部门审核
const isWithDept = ref('1');
//部门级别
const deptId = ref(0);
//一批审批节点
const processNodes = ref<processNode[]>([]);
//缓存的审批节点
const cacheProcessNode = ref<processNode>({
  nodeName: "",
  isWithDept: false,
  deptPriority: 0,
  nodePriority: 0,
});

//为不能自动绑定数据的el-input绑定数据
const nodeNameValue = (value) => {
  nodeName.value = value;
  console.log("审批节点名称", nodeName.value);
};

//添加审批节点
const addProcessNode = () => {
  //如果没有输入节点名称，直接返回
  if (nodeName.value === "") {
    return;
  }
  //把审批节点添加到processNodes中
  cacheProcessNode.value.nodeName = nodeName.value;
  cacheProcessNode.value.isWithDept = isWithDept.value === '0' ? true : false;
  cacheProcessNode.value.deptPriority = deptId.value;
  cacheProcessNode.value.nodePriority = nodePriority.value;
  //如果节点优先级已经存在，直接返回
  if (processNodes.value.some(node => node.nodePriority === cacheProcessNode.value.nodePriority)) {
    ElMessage({
      type: 'warning',
      message: '该节点优先级已存在，请重新输入',
    })
    return;
  }
  const newNode = JSON.parse(JSON.stringify(cacheProcessNode.value));

  processNodes.value.push(newNode);
  console.log("添加审批节点", cacheProcessNode.value);
  //清空审批节点信息
  nodeName.value = "";
  nodePriority.value = nodePriority.value + 1;
  isWithDept.value = '1';
  deptId.value = 0;
  processNodes.value.sort((a, b) => a.nodePriority - b.nodePriority)
};
//待被删去的审批节点
const readyForDelete = ref(0);
//删除审批节点
const deleteProcessNode = () => {
  //如果没有选中审批节点，直接返回
  if (readyForDelete.value === null) {
    ElMessage({
      type: 'warning',
      message: '请选择要删除的审批节点',
    })
    return;
  }
  console.log("删除审批节点", readyForDelete.value);
  //把选中的审批节点从processNodes中删除
  let index = processNodes.value.findIndex(
    (node) => node.nodePriority === readyForDelete.value
  );
  processNodes.value.splice(index, 1);
  console.log("删除审批节点", readyForDelete.value);
  //清空选中的审批节点
  readyForDelete.value = 0;
  processNodes.value.sort((a, b) => a.nodePriority - b.nodePriority)
}

const getTypesList = async () => {
  const res = await getAllTypes();
  if (res.flag = true) {
    tableData.value = res.result.map((item) => {
      return {
        id: item.id,
        name: item.flowType,
      };
    });
  } else {
    ElMessage({
      type: 'error',
      message: '获取审批类型失败',
    })
  }
}

//部门信息
const deptLayers = ref(0);
const getDeptLayers = async () => {
  //获取部门的层级
  const res = await getTreeHeight();
  if (res.flag === true) {
    deptLayers.value = res.result;
  } else {
    ElMessage({
      type: 'error',
      message: '获取部门层级失败',
    })
  }
}
// 添加防抖优化
let resizeObserver: ResizeObserver | null = null
onMounted(() => {
  nextTick(() => {
    const scrollWrap = scrollbar.value?.$el?.querySelector('.el-scrollbar__wrap')
    if (scrollWrap) {
      // 监听内容变化
      resizeObserver = new ResizeObserver(checkScroll)
      resizeObserver.observe(scrollWrap)

      // 初始化检查
      checkScroll()

      // 监听滚动容器本身的滚动事件（双重保险）
      scrollWrap.addEventListener('scroll', handleScroll)
    }
  })
  //从后端获取审批类型数据
  getTypesList();
  //从数据库拿到部门的最高级
  getDeptLayers();
});
</script>

<style scoped>
.el-style {
  width: 240px;
  margin-left: 10px;
}

.el-table .odd-row {
  --el-table-tr-bg-color: #e7f4fc;
}

.el-table .even-row {
  --el-table-tr-bg-color: white;
}

.container {
  display: flex;
  flex-direction: row;
  height: 75vh;
  width: 100%;
  /* background-color: pink; */
}

.table {
  margin: 1%;
  background-color: rgb(217, 244, 249);
  width: 50%;
  height: 90%;
  border-radius: 10px;
  border: 1px solid rgb(194, 194, 194);
  /* 边框 */
}

.table .el-table {
  border-radius: 10px;
}

.item,
.board {
  margin: 1%;
  background-color: rgb(217, 244, 249);
  width: 50%;
  height: 90%;
  border-radius: 10px;
  border: 1px solid rgb(194, 194, 194);
  /* 边框 */
  margin: 1%;
  overflow-y: auto;
  /* 当内容超出高度时显示垂直滚动条 */
  overflow-x: hidden;
  /* 隐藏水平滚动条 */
}

.item .item-content {
  margin: 1% 1% 1% 3%;
}

.item .item-timestamp p {
  font-size: 25px;
  margin: 1% 1% 1% 3%;
  color: #021148;
}

.item .item-timestamp .el-timeline {
  margin: 2% 1% 1% 3%;
}

.board {
  display: flex;
  justify-content: center;
  align-items: center;
}

/* 修改滚动指示器样式 */
.scroll-indicator {
  position: absolute;
  bottom: 20px;
  right: 20px; /* 改为右侧定位 */
  animation: bounce 2s infinite;
  opacity: 0.8;
  z-index: 1; /* 确保在内容上方 */
}
.el-scrollbar{
  height: 100%;
}

@keyframes bounce {
  0%,
  20%,
  50%,
  80%,
  100% {
    transform: translateY(0); /* 移除水平位移 */
  }
  40% {
    transform: translateY(-15px);
  }
  60% {
    transform: translateY(-7px);
  }
}

/* 确保滚动容器有相对定位 */
.item {
  position: relative;
}
</style>